﻿using AutoMapper;
using King.AdminSite.Models;
using King.Data;
using King.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace King.AdminSite.Controllers
{
    [Authorize]
    public class TagsController : AdminBaseController
    {
        private IPermission _permission;
        private IMapper _mapper;
        private IRepository<Tags> _tagsRepository;

        public TagsController(IMapper mapper, IPermission permission, IRepository<Tags> tagsRepository)
        {
            _mapper = mapper;
            _permission = permission;
            _tagsRepository = tagsRepository;
        }

        [PermissionFilter(MenuCode.Content_Tags, PermissionType.View)]
        public IActionResult Index()
        {

            ViewData[PageCode.PAGE_Button_Add] = _permission.CheckPermission(LoginUser, MenuCode.Content_Tags, PermissionType.Add);
            ViewData[PageCode.PAGE_Button_Edit] = _permission.CheckPermission(LoginUser, MenuCode.Content_Tags, PermissionType.Edit);
            ViewData[PageCode.PAGE_Button_Delete] = _permission.CheckPermission(LoginUser, MenuCode.Content_Tags, PermissionType.Delete);

            return View();
        }

        [PermissionFilter(MenuCode.Content_Tags, PermissionType.View)]
        public async Task<JsonResult> GetList()
        {
            AjaxResultList result = new AjaxResultList();

            var query = await _tagsRepository.GetListAsync(p => p.IsDelete == false, p => p.TagsId);

            var data = _mapper.Map<List<TagsModel>>(query);

            result.Code = (int)ResultCode.Success;
            result.Msg = "成攻";
            result.Count = query.Count();
            result.Data = data;

            return Json(result);
        }


        public async Task<ActionResult> Edit(int id)
        {
            var model = new TagsModel();

            if (id > 0)
            {
                var query = await _tagsRepository.GetOneAsync(id);
                model = _mapper.Map<TagsModel>(query);

            }

            return View(model);
        }

        [HttpPost, ActionName("Edit")]
        [PermissionFilter(MenuCode.Content_Tags, PermissionType.Edit)]
        public async Task<ActionResult> EditPost(int id, TagsModel input)
        {
            AjaxResult result = new AjaxResult() { Code = (int)ResultCode.ParmsError, Msg = "失败" };

            var editmodel = await _tagsRepository.GetOneAsync(id);

            editmodel.TagsName = input.TagsName;        
            editmodel.IsActive = input.IsActive;
            editmodel.Sort = input.Sort;
            editmodel.UpdateBy = LoginUser.UserName;
            editmodel.UpdateTime = DateTime.Now;

            if (await _tagsRepository.UpdateAsync(editmodel))
            {
                result.Code = (int)ResultCode.Success;
                result.Msg = "修改成功";
            }

            return Json(result);
        }


        [HttpPost, ActionName("Add")]
        [PermissionFilter(MenuCode.Content_Tags, PermissionType.Add)]
        public async Task<ActionResult> AddPost(TagsModel input)
        {
            AjaxResult result = new AjaxResult() { Code = (int)ResultCode.ParmsError, Msg = "失败" };

            var model = new Tags();
            model.TagsName = input.TagsName;

            model.IsActive = input.IsActive;
            model.Sort = input.Sort;
            model.CreationBy = LoginUser.UserName;
            model.CreationTime = DateTime.Now;

            if ((await _tagsRepository.AddAsync(model)).TagsId > 0)
            {
                result.Code = (int)ResultCode.Success;
                result.Msg = "添加成功";
            }

            return Json(result);
        }

        [HttpPost]
        [PermissionFilter(MenuCode.Content_Tags, PermissionType.Delete)]
        public async Task<JsonResult> Delete(int isAll = 0, int id = 0)
        {
            AjaxResult result = new AjaxResult() { Code = (int)ResultCode.ParmsError, Msg = "参数不全" };           

            if (isAll == 0)
            {
                if (id > 0)
                {
                    var sql = $"update {nameof(Tags)} set {nameof(Tags.IsDelete)}=1 where {nameof(Tags.TagsId)}={id}";

                    if (await _tagsRepository.ExecuteSqlAsync(sql) > 0)
                    {
                        log.Info($"删除Ct_Tags:id={id}");
                        result.Code = (int)ResultCode.Success;
                        result.Msg = "删除成功";
                    }

                }
            }
            else
            {
                var ids = Request.Form["ids[]"].ToArray();
                var strNums = string.Join(",", Array.ConvertAll(ids, int.Parse));
                var sql = $"update {nameof(Tags)} set {nameof(Tags.IsDelete)}=1 where {nameof(Tags.TagsId)} in ({strNums})";
                if (await _tagsRepository.ExecuteSqlAsync(sql) > 0)
                {
                    log.Info($"批量删除Ct_Tags:id={strNums}");
                    result.Code = ResultCode.Success.GetHashCode();
                    result.Msg = "删除成功";
                }
            }

            return Json(result);
        }
    }
}